package jch.learn.java.advanced.chapter2_InputAndOutput.textFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Scanner;

// 以文本格式存储对象
public class TextFileTest {

    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        Employee[] staff = new Employee[3];
        staff[0] = new Employee("张三", 67000, 1900, 12, 15);
        staff[1] = new Employee("李四", 56000, 2010, 11, 23);
        staff[2] = new Employee("赵武", 89000, 2021, 11, 11);

        String path = TextFileTest.class.getResource("/chapter2/employee.dat").getPath();
        // 创建对象格式化形式文本输出流 | 打印员工信息到文件
        try (PrintWriter out = new PrintWriter(path, StandardCharsets.UTF_8.name())) {
            writeData(staff, out);
        }

        // 读取文件信息输出到控制台
        try (Scanner in = new Scanner(new FileInputStream(path), StandardCharsets.UTF_8.name())) {
            Employee[] newStaff = readData(in);
            for (Employee e:newStaff) { // 输入出信息到控制台
                System.out.println(e);
            }
        }
    }

    // 读取输入数据
    private static Employee[] readData(Scanner in) {
        int n = in.nextInt(); // 数组大小
        in.nextLine(); // 返回当前行之前输入
        Employee[] employees = new Employee[n];
        for (int i = 0; i < n; i++) {
            employees[i] = readEmployee(in);
        }
        return employees;
    }

    // 读取输入员工信息
    private static Employee readEmployee(Scanner in) {
        String line = in.nextLine();
        String[] tokens = line.split("\\|");
        String name = tokens[0];
        double salary = Double.parseDouble(tokens[1]);
        LocalDate hireDate = LocalDate.parse(tokens[2]);
        int year = hireDate.getYear();
        int month = hireDate.getMonthValue();
        int day = hireDate.getDayOfMonth();
        return new Employee(name, salary, year, month, day);
    }

    /**
     * 写入数据
     *
     * @param staff employee 员工信息数组
     * @param out   将对象的格式化表示形式打印到文本输出流。
     */
    private static void writeData(Employee[] staff, PrintWriter out) {
        out.println(staff.length); // staff 长度
        for (Employee e : staff) {
            writeEmployee(out, e);
        }
    }

    /**
     * 写入单个员工数据
     *
     * @param out 将对象的格式化表示形式打印到文本输出流
     * @param e   员工信息
     */
    private static void writeEmployee(PrintWriter out, Employee e) {
        out.println(e.getName() + "|" + e.getSalary() + "|" + e.getHireDay());
    }

}
